package com.tellhow.monitorserverqh.service.impl;

import com.alibaba.fastjson.JSON;
import com.tellhow.monitorserverqh.mapper.MonitorServerMapper;
import com.tellhow.monitorserverqh.model.Infos;
import com.tellhow.monitorserverqh.model.MonitorServerModel;
import com.tellhow.monitorserverqh.model.RemoteExecuteCommandutil;
import com.tellhow.monitorserverqh.model.Servers;
import com.tellhow.monitorserverqh.service.IMonitorServer;
import com.tellhow.monitorserverqh.service.ISms;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author:gnplum
 * @Date: 2023/4/27  11:36
 * @Version 1.0
 */

@Configuration
@ConfigurationProperties(prefix = "server")
//如果只有一个主配置类文件，@PropertySource可以不写
@PropertySource("classpath:application.properties")
@Data
@Service
public class MonitorServerImpl implements IMonitorServer {
    private static final Log logger = LogFactory.getLog(MonitorServerImpl.class);

    @Resource
    MonitorServerMapper monitorServerMapper;
    @Autowired
    ISms iSms;
    //配置文件获取监控ip
    private Map<String, Object> ips = new HashMap<>();
    //配置文件获取监控的java进程
    private Map<String, Object> jars = new HashMap<>();
    @Autowired
    private ApplicationContext ioc;

    @Autowired
    private RemoteExecuteCommandutil Commandutil;

    @Autowired
    private Servers servers;

    @Value("${server.info.ip}")
    private String runIp;

    @Transactional
    @Override
    public void runMonitorServer() {
        try {
            //监控服务器ping
            logger.info(">> 监控服务器ping......");
            MonitorPing();

            //监控服务器java进程
            logger.info(">> 监控服务器java进程......");
            MonitorJavaProcess();

            //监控异常内容插入短信表
            logger.info(">> 监控异常内容插入短信表......");
            iSms.sendSMS();

        } catch (Exception e) {
            logger.error(e.getCause() + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 监控服务器连通性ping
     */
    private void MonitorPing() {
        MonitorServerModel monitorServerModel = new MonitorServerModel();
        //Servers servers = ioc.getBean("servers", Servers.class);
        String serip = "";
        try {
            for (Infos infos : servers.infos) {
                serip = infos.getIp();//监控的ip
                logger.info(">> 当前监控ip：[" + serip + "]......");
                monitorServerModel.setIp(serip);
                monitorServerModel.setWarn_type(1);
                monitorServerModel.setService_url("");
                monitorServerModel.setService_type(3);
                monitorServerModel.setDelflag(0);
                monitorServerModel.setRun_server(runIp);

                //ping
                InetAddress geek = InetAddress.getByName(serip);
                if (geek.isReachable(5000)) {
                    logger.info(">> [" + serip + "]可连通！");
                    monitorServerModel.setService_status(0);
                    monitorServerModel.setService_desc("可连通！");
                } else {
                    logger.info(">> [" + serip + "]不可连通！");
                    monitorServerModel.setService_status(1);
                    monitorServerModel.setService_desc("无法连通！");
                }

                //服务器监控记录
                logger.info(">> 服务器监控记录插入：" + JSON.toJSONString(monitorServerModel));
                monitorServerMapper.InsertMonitorServer(monitorServerModel);

            }
        } catch (Exception e) {
            logger.error(">>监控服务器连通性异常-" + e.getStackTrace() + e.getMessage());
        }
    }

    /**
     * 监控服务器java进程
     */
    private void MonitorJavaProcess() {
        MonitorServerModel monitorServerModel = new MonitorServerModel();
        //Servers servers = ioc.getBean("servers", Servers.class);
        String serip = "";
        Integer serPort = 0;
        String serUser = "";
        String serPwd = "";
        String serJars = "";
        String command = "";
        try {
            for (Infos infos : servers.infos) {
                serip = infos.getIp();
                serPort = infos.getPort();
                serUser = infos.getUser();
                serPwd = infos.getPwd();
                serJars = infos.getJar();

                String[] jars = serJars.split(",");
                List<String> jarlist = Arrays.asList(jars);
                logger.info("jarlist=" + jarlist);
                for (String jar : jarlist) {
                    command = "ps -ef|grep " + jar;

                    monitorServerModel.setIp(serip);
                    monitorServerModel.setWarn_type(2);
                    monitorServerModel.setService_url(jar);
                    monitorServerModel.setService_type(3);
                    monitorServerModel.setDelflag(0);
                    monitorServerModel.setRun_server(runIp);

                    //登录linux
                    String cmdInformation = null;
                    try {
                        Commandutil = new RemoteExecuteCommandutil(serip, serPort, serUser, serPwd);
                        cmdInformation = Commandutil.execute(command);
                        logger.info(">> 执行命令：" + command + "；结果：" + cmdInformation);
                    } catch (Exception e) {
                        return;
                    }
/*
                    if (StringUtils.isBlank(cmdInformation)) {
                        monitorServerModel.setService_status(1);
                        monitorServerModel.setService_desc("JAVA进程[" + jar + "]已停止");
                    } else {
                        monitorServerModel.setService_status(0);
                        monitorServerModel.setService_desc("JAVA进程[" + jar + "]正常");
                    }*/

                    //找java执行后运行的端口号是否存在
                    //int javaprocessExist = cmdInformation.indexOf("server.port");//jar
                    int javaprocessExist = cmdInformation.indexOf("org.apache.catalina.startup.Bootstrap start");//war
                    if (javaprocessExist >= 0) {
                        monitorServerModel.setService_status(0);
                        monitorServerModel.setService_desc("进程[" + jar + "]正常");
                    } else {
                        monitorServerModel.setService_status(1);
                        monitorServerModel.setService_desc("进程[" + jar + "]已停止");
                    }

                    //服务器监控记录
                    logger.info(">> JAVA进程监控记录插入：" + JSON.toJSONString(monitorServerModel));
                    monitorServerMapper.InsertMonitorServer(monitorServerModel);
                }
            }
        } catch (Exception ex) {
            logger.error(">>监控服务器java进程异常-" + ex.getStackTrace() + ex.getMessage());
        }
    }
}
